package com.ruoyi.dataMain.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import com.ruoyi.baseMain.service.IBaseAccountService;
import com.ruoyi.common.excel.DefaultExcelResult;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.dataMain.domain.bo.DataUploadBo;
import com.ruoyi.dataMain.domain.dto.JlConsumptionOriginalDto;
import com.ruoyi.dataMain.domain.dto.JlxhConsumptionOriginalDto;
import com.ruoyi.dataMain.domain.dto.KsConsumptionOriginalDto;
import com.ruoyi.dataMain.domain.dto.TxConsumptionOriginalDto;
import com.ruoyi.dataMain.domain.vo.DataUploadVo;
import com.ruoyi.dataMain.listener.*;
import com.ruoyi.dataMain.service.IDataConsumptionOriginalService;
import com.ruoyi.dataMain.service.IDataUploadService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import net.lingala.zip4j.core.ZipFile;
import org.apache.poi.util.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dataMain.domain.vo.DataConsumptionVo;
import com.ruoyi.dataMain.domain.bo.DataConsumptionBo;
import com.ruoyi.dataMain.service.IDataConsumptionService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 消耗总表
 *1
 * @author linziheng
 * @date 2024-01-03
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dataMain/consumption")
public class DataConsumptionController extends BaseController {

    private final IDataConsumptionService iDataConsumptionService;
    private final IDataUploadService iDataUploadService;
    private final IDataConsumptionOriginalService iDataConsumptionOriginalService;

    /**
     * 转户处理*
     * @return
     */
    @GetMapping("/secondary")
    public R secondary() {
        iDataConsumptionOriginalService.secondary();
        return R.ok();
    }

    /**
     * 上传zip包
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public ExcelResult<TxConsumptionOriginalDto> uploadFile(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //文件跟目录

        //保存计算上传数据
        DataUploadBo dataUploadBo = new DataUploadBo();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        dataUploadBo.setUploadDate(formattedDate);
        List<DataUploadVo> dataUploadVos= iDataUploadService.queryList(dataUploadBo);
        dataUploadBo.setBitch(formattedDate+"-"+(dataUploadVos.size() + 1));

        //files对应前端的key
        MultipartFile multipartFile = multipartRequest.getFile("file");
        String zipName = multipartFile.getOriginalFilename();
//        String dest = "C:\\Users\\linziheng\\Desktop\\"+dataUploadBo.getBitch()+"\\";
        String dest = "/Users/linziheng/Desktop/"+dataUploadBo.getBitch()+"/";

        dataUploadBo.setPath(dest+zipName);

        File file = new File(dest+zipName);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);

        //解压
        ZipFile zFile = new ZipFile(file);
//        zFile.setFileNameCharset("utf-8");
        zFile.setFileNameCharset("GBK");
        File destDir = new File(dest);
        zFile.extractAll(dest);
        String[] projectName = new String[]{"tx","jl(消耗明细)","ks","jl"};
        // 处理各个目录路径
        ExcelResult<TxConsumptionOriginalDto> res = getTxFile(dest,projectName,dataUploadBo.getBitch());
        iDataUploadService.insertByBo(dataUploadBo);
        return res;
    }
       public ExcelResult<TxConsumptionOriginalDto> getTxFile(String dest,String[] projectName,String bitch) throws IOException {
           ExcelResult<TxConsumptionOriginalDto> tx = null;
           for (String s : projectName) {
               // 指定tx目录路径
               String directoryPath = dest+s;
               // 创建tx File对象表示目录
               File directory = new File(directoryPath);

               // 确保目录存在且确实是一个目录
               if (directory.exists() && directory.isDirectory()) {
                   // 获取目录下所有文件和文件夹的名称
                   String[] fileNames = directory.list();
                   System.out.println("----"+s+"---start");

                   // 打印所有文件和文件夹的名称
                   if (fileNames != null) {
                       for (String fileName : fileNames) {
                           //  System.out.println("tx目录下："+fileName);
                           File item = new File(directoryPath+"/"+fileName);
                           FileInputStream input = new FileInputStream(item);
                           if(fileName.charAt(0)!='.' && fileName.charAt(0)!='~'){
                               System.out.println(fileName);
                               MultipartFile targetFiles = new MockMultipartFile("targetFiles",item.getName(),null, IOUtils.toByteArray(input));

                               switch (s) {
                                   case "tx":
                                       // 腾讯文件夹数据导入
                                        tx = ExcelUtil.importExcel(targetFiles.getInputStream(), TxConsumptionOriginalDto.class, new DataConsumptionTxImportListener(directoryPath+"/"+fileName,bitch));
                                       break;
                                   case "jl(消耗明细)":
                                       // jl(消耗明细)文件夹数据导入
                                       ExcelResult<JlxhConsumptionOriginalDto> jlxh = ExcelUtil.importExcel(targetFiles.getInputStream(), JlxhConsumptionOriginalDto.class, new DataConsumptionJlxhImportListener(directoryPath+"/"+fileName,bitch));
                                       break;
                                   case "ks":
                                       // ks文件夹数据导入
                                       ExcelResult<KsConsumptionOriginalDto> ks = ExcelUtil.importExcel(targetFiles.getInputStream(), KsConsumptionOriginalDto.class, new DataConsumptionKsImportListener(directoryPath+"/"+fileName,bitch));
                                       break;
                                   case "jl":
                                       // jl文件夹数据导入
                                       ExcelResult<JlConsumptionOriginalDto> jl = ExcelUtil.importExcel(targetFiles.getInputStream(), JlConsumptionOriginalDto.class, new DataConsumptionJlImportListener(directoryPath+"/"+fileName,bitch));
                                       break;
                                   default:
                               }

                           }

                       }
                   }
                   System.out.println("----"+s+"---end");
               } else {
                   System.out.println("The specified directory does not exist or is not a directory.");
               }
           }
            return tx;
        }
    /**
     * 查询消耗总表列表
     */
    @SaCheckPermission("dataMain:consumption:list")
    @GetMapping("/list")
    public TableDataInfo<DataConsumptionVo> list(DataConsumptionBo bo, PageQuery pageQuery) {
        return iDataConsumptionService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出消耗总表列表
     */
    @SaCheckPermission("dataMain:consumption:export")
    @Log(title = "消耗总表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DataConsumptionBo bo, HttpServletResponse response) {
        List<DataConsumptionVo> list = iDataConsumptionService.export(bo);
        ExcelUtil.exportExcel(list, "消耗总表", DataConsumptionVo.class, response);
    }
    /**
     * 导入数据
     *
     * @param file          导入文件
     */
    @Log(title = "开户导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelResult<DataConsumptionVo> result = ExcelUtil.importExcel(file.getInputStream(), DataConsumptionVo.class, new DataConsumptionImportListener());
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "消耗总表", DataConsumptionVo.class, response);
    }
    /**
     * 获取消耗总表详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("dataMain:consumption:query")
    @GetMapping("/{id}")
    public R<DataConsumptionVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iDataConsumptionService.queryById(id));
    }

    /**
     * 新增消耗总表
     */
    @SaCheckPermission("dataMain:consumption:add")
    @Log(title = "消耗总表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DataConsumptionBo bo) {
        return toAjax(iDataConsumptionService.insertByBo(bo));
    }

    /**
     * 修改消耗总表
     */
    @SaCheckPermission("dataMain:consumption:edit")
    @Log(title = "消耗总表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DataConsumptionBo bo) {
        return toAjax(iDataConsumptionService.updateByBo(bo));
    }

    /**
     * 删除消耗总表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("dataMain:consumption:remove")
    @Log(title = "消耗总表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iDataConsumptionService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
